<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href>订单管理</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>订单列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card v-loading="loading">
      <!-- 行     gutter是格式这里的间隔-->
      <el-row :gutter="20">
        <!-- 列 -->
        <el-col :span="8">
          <!-- 搜索框 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getOrder">
            <el-button slot="append" icon="el-icon-search" @click="getOrder"></el-button>
          </el-input>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="orderList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="订单编号" prop="order.orderNumber" width="180px"></el-table-column>
        <el-table-column label="下单时间" prop="order.orderCreationTime" width="90px">
          <template slot-scope="scope">{{scope.row.order.orderCreationTime | dateFormat}}</template>
        </el-table-column>
        <el-table-column label="商品名称" prop="productName" width="100px"></el-table-column>
        <el-table-column label="订单金额" prop="order.orderPrice" width="100px"></el-table-column>
        <el-table-column label="下单用户" prop="order.name" width="90px"></el-table-column>
        <el-table-column label="订单状态" prop="order.orderState" width="100px">
          <template slot-scope="scope">
            <el-tag type="danger" v-if="scope.row.order.orderState === 0">未付款</el-tag>
            <el-tag type="warning" v-if="scope.row.order.orderState === 1" @click="updataSendGoods(scope.row._id,scope.row.order.orderState)">未发货</el-tag>
            <el-tag type="warning" v-if="scope.row.order.orderState === 2" @click="updataSendGoods(scope.row._id,scope.row.order.orderState)">未发货</el-tag>
            <el-tag
              v-if="scope.row.order.orderState === 3"
              @click="updataSendGoods(scope.row._id,scope.row.order.orderState)"
            >已发货</el-tag>
            <el-tag type="success" v-if="scope.row.order.orderState === 4">已收货</el-tag>
            <el-tag type="success" v-if="scope.row.order.orderState === 5">交易完成</el-tag>
            <el-tag type="info" v-if="scope.row.order.orderState === 6">待评价</el-tag>
            <el-tag type="info" v-if="scope.row.order.orderState === 7">已评价</el-tag>
            <el-tag type="warning" v-if="scope.row.order.orderState === 8">退换货</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="有效期时间" prop="order.termOfValidity" width="90px">
          <template slot-scope="scope">{{scope.row.order.termOfValidity | dateFormat}}</template>
        </el-table-column>

        <el-table-column label="操作" width="180px">
          <!-- 作用域插槽 -->
          <!-- slot-scope="scope" -->
          <template slot-scope="scope">
            <el-popover placement="top-start" width="150px" trigger="hover" content="修改订单价格等信息">
              <!-- <el-button slot="reference">hover 激活</el-button> -->
              <!-- 修改订单价格与更新发货状态 -->
              <el-button
                slot="reference"
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showOrderEdit(scope.row)"
              ></el-button>
            </el-popover>

            <!-- 修改订单地址按钮 -->
            <el-popover placement="top-start" width="150px" trigger="hover" content="修改收货地址">
              <el-button
                slot="reference"
                type="primary"
                icon="el-icon-map-location"
                size="mini"
                @click="showBox(scope.row.order.orderNumber)"
              ></el-button>
            </el-popover>
            <!-- 物流详情 -->
            <el-popover placement="top-start" width="150px" trigger="hover" content="物流信息">
              <el-button
                slot="reference"
                type="success"
                icon="el-icon-truck"
                size="mini"
                @click="showProgress(scope.row._id)"
              ></el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 修改收货地的对话框 -->
    <el-dialog title="修改地址" :visible.sync="addressVisible" width="50%">
      <el-form
        :model="addressForm"
        :rules="addressFormRules"
        ref="addressFormRules"
        label-width="100px"
      >
        <el-form-item label="省市区/县" prop="address">
          <el-cascader
            placeholder="可搜索关键字"
            :options="citydata"
            filterable
            v-model="addressForm.address"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="详情地址" prop="addressDetails">
          <el-input v-model="addressForm.addressDetails"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addressclose">取 消</el-button>
        <el-button type="primary" @click="addressEdit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 显示物流进度对话框 -->
    <el-dialog title="物流进度" :visible.sync="progressVisible" width="50%">
      <el-timeline :reverse="reverse">
        <el-timeline-item
          v-for="(progressInfo, index) in progressInfo"
          :key="index"
          :timestamp="progressInfo.timestamp"
        >{{progressInfo.content}}</el-timeline-item>
      </el-timeline>
      <span slot="footer" class="dialog-footer">
        <el-button @click="progressClose">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 修改价格与发货对话框 -->
    <el-dialog title="修改订单价格" :visible.sync="goodsInfoEditVisible" width="50%">
      <el-form :model="orderForm" :rules="orderFormRules" ref="orderFormRules" label-width="100px">
        <el-form-item label="订单价格" prop="orderPrice">
          <el-input v-model.number="orderForm.orderPrice" type="number"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="goodsInfoEditClose">取 消</el-button>
        <el-button @click="goodsInfoEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import citydata from './citydata.js'
import {
  getOrderList,
  addressEdit,
  updateOrderPrice,
  updateOrderSendGoods
} from '../../api/order/list.js'
export default {
  data() {
    return {
      loading: false,
      queryInfo: {
        query: null,
        // 当前的页数
        pageNum: 1,
        // 当前每页显示多少条
        pageSize: 5
      },
      total: 0,
      orderList: [],
      addressVisible: false,
      progressVisible: false,
      goodsInfoEditVisible: false,
      addressForm: {
        id: '',
        address: [],
        addressDetails: ''
      },
      orderForm: {
        orderPrice: 0
      },
      //   物流显示 时间线 倒序显示
      reverse: false,
      //  物流进度数据
      progressInfo: [
        {
          content: '活动按期开始',
          timestamp: '2018-04-15'
        },
        {
          content: '通过审核',
          timestamp: '2018-04-13'
        },
        {
          content: '创建成功',
          timestamp: '2018-04-11'
        }
      ],
      //   图片上传组件的headers请求头对象（里面可以包含Token）
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      //   表单验证规则
      addressFormRules: {
        address: [{ required: true, message: '请选择省市区', trigger: 'blur' }],
        addressDetails: [
          { required: true, message: '请填写详情地址', trigger: 'blur' }
        ]
      },
      // 订单价格验证规则
      orderFormRules: {
        orderPrice: [
          { required: true, message: '请输入订单价格', trigger: 'blur' }
        ]
      },
      citydata
    }
  },
  created() {
    this.getOrder()
  },
  methods: {
    getOrder() {
      this.loading = true
      getOrderList(this.queryInfo).then(res => {
        this.loading = false
        console.log(res.data)
        if (!res.data.success) {
          return this.$message.error('获取订单列表失败')
        }
        this.orderList = res.data.data
        this.total = res.data.Total
        // console.log(this.orderList)
        // console.log(this.total)
      })
    },
    // 展示订单修改价格信息
    showOrderEdit(item) {
      console.log(item)
      if (item.order.orderState === 0) {
        this.goodsInfoEditVisible = true
        this.orderForm.orderPrice = item.order.orderPrice
        this.orderForm.id = item._id
        console.log(this.orderForm)
      } else {
        return this.$message.error('此订单不可修改价格！')
      }
    },
    // 关闭订单修改价格与发货
    goodsInfoEditClose() {
      this.goodsInfoEditVisible = false
    },
    // 更新订单价格
    goodsInfoEdit() {
      console.log(this.orderForm)
      this.loading = true
      updateOrderPrice(this.orderForm).then(res => {
        this.goodsInfoEditVisible = false
        this.loading = false
        console.log(res)
        if (res.data.modified <= 0) {
          return this.$message.error('订单价格修改失败！')
        }
        this.$message.success('订单价格修改完成')
        this.getOrder()
      })
    },
    // 更新发货状态
    updataSendGoods(id, valState) {
      console.log(valState)
      const sendGoods = {}
      if (valState === 1) {
        this.$confirm('将此订单更新为已发货状态吗?', '发货状态', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(res => {
          console.log(res)
          if (res !== 'confirm') return
          this.loading = true
          console.log('更新为已发货状态')
          sendGoods.id = id
          sendGoods.state = 3
          updateOrderSendGoods(sendGoods).then(res => {
            this.loading = false
            console.log(res)
            if (res.data.modified <= 0) {
              return this.$message.error('更新订单发货状态失败！')
            }
            this.$message.success('订单更新为已发货完成')
            this.getOrder()
          })
        })
      } else if (valState === 3) {
        this.$confirm('将此订单取消已发货更新为待发货状态吗?', '发货状态', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(res => {
          console.log(res)
          if (res !== 'confirm') return
          this.loading = true
          console.log('更新为取消发货，更新为待发货')
          sendGoods.id = id
          sendGoods.state = 2
          updateOrderSendGoods(sendGoods).then(res => {
            this.loading = false
            console.log(res)
            if (res.data.modified <= 0) {
              return this.$message.error('更新订单发货状态失败！')
            }
            this.$message.success('订单更新为待发货状态')
            this.getOrder()
          })
        })
      } else if (valState === 2) {
        this.$confirm('将此订单更新为已发货状态吗?', '发货状态', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(res => {
          console.log(res)
          if (res !== 'confirm') return
          this.loading = true
          console.log('更新为已发货状态')
          sendGoods.id = id
          sendGoods.state = 3
          updateOrderSendGoods(sendGoods).then(res => {
            this.loading = false
            console.log(res)
            if (res.data.modified <= 0) {
              return this.$message.error('更新订单发货状态失败！')
            }
            this.$message.success('订单更新为已发货完成')
            this.getOrder()
          })
        })
      }
    },
    // 展示修改地址的对话框
    showBox(id) {
      //   this.$refs.addressFormRules.resetFields()
      this.addressForm = {}
      this.addressVisible = true
      console.log(id)
      this.addressForm.id = id
    },
    // 展示显示物流进度圣诞框
    showProgress(id) {
      console.log(id)
      this.progressVisible = true
    },
    // 关闭物流进度对话框
    progressClose() {
      this.progressVisible = false
    },
    removeCouponById(id) {
      console.log(id)
      this.$confirm('此操作将永久删除该优惠券, 是否继续?', '删除优惠券提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        console.log(res)
        if (res !== 'confirm') return
        this.loading = true
        // delCouponByid(id).then(res => {
        //   console.log(res)
        //   this.loading = false
        //   if (res.data.deleted === 0) return this.$message.error('删除优惠券失败')
        //   // 重新获优惠券列表
        //   this.getCoupon()
        //   this.$message.success('删除指定优惠券完成')
        // })
      })
      this.loading = false
    },
    upperShelfStateChange(item) {
      //   console.log(item)
      //   const params = {
      //     id: item._id,
      //     UpperShelfState: item.upShelves
      //   }
      //   console.log(params)
      //   updateCouponUpShelvesState(params).then(res => {
      //     // console.log(res)
      //     if (res.data.data.modified > 0) {
      //       this.$message.success('商品上架状态更新成功')
      //     }
      //   })
    },
    handleSizeChange(newSize) {
      console.log(newSize)
      this.queryInfo.pageSize = newSize
      this.getOrder()
    },
    handleCurrentChange(newPage) {
      //   console.log(newPage)
      this.queryInfo.pageNum = newPage
      //   console.log(this.queryInfo.pageNum)
      this.getOrder()
    },
    addressclose() {
      this.addressVisible = false
      this.$refs.addressFormRules.resetFields()
    },
    addressEdit() {
      this.addressVisible = false
      console.log(this.addressForm)
      // 将数据转换成json类型
      if (this.addressForm.address.length > 0) {
        const data = this.addressForm.address
        if (data.length === 3) {
          this.addressForm.addressInfo = {
            provinceName: data[0],
            cityName: data[1],
            countyName: data[2]
          }
        } else if (data.length === 2) {
          this.addressForm.addressInfo = {
            provinceName: data[0],
            cityName: data[1],
            countyName: ''
          }
        } else if (data.length === 1) {
          this.addressForm.addressInfo = {
            provinceName: data[0],
            cityName: '',
            countyName: ''
          }
        }
      }
      console.log(this.addressForm)
      this.loading = true
      addressEdit(this.addressForm).then(res => {
        this.loading = false
        console.log(res)
        if (!res.data.success) {
          return this.$message.error('修改订单收货地址失败')
        }
        return this.$message.success('修改收货地址完成')
      })
      //  发送修改后的地址到服务器
    }
  }
}
</script>
<style lang="less" scoped>
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.el-cascader {
  width: 100%;
}
.el-button--mini {
  margin-right: 5px;
}
</style>
